<script setup name="Role">
import {
  addRole,
  updateRoleDataScope,
  delRole,
  getRole,
  updateRole,
  getDeptIdsByRoleId,
  getRolePageList, updateRoleMenu,
  getAllMenuTree, getRoleMenuIds
} from "@/api/system/role"
import {getDeptTree} from "@/api/system/dept.js"
import {collectPropValues} from "@/utils/ruoyi.js"
import {isNull} from "@/utils/validate.js";

const {proxy} = getCurrentInstance()
const {dataScope} = proxy.useDict(['dataScope', false])

const roleList = ref([])
const openRoleDialog = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const title = ref('')
//弹出框中的 tree控件相关公共变量
const treeExpand = ref(false)
const treeCheckStrictly = ref(false)
const treeNodeAll = ref(false)
const treeCheckedKeys = ref([])
const treeKeys = ref([])
//菜单权限所需变量
const menuOptions = ref([])
const openMenuDialog = ref(false)
const menuRef = ref(null)
//数据权限权限所需变量
const deptOptions = ref([])
const openDataScopeDialog = ref(false)
const deptRef = ref(null)


/** 数据权限*/
const getDataScope = (value) => {
  if (!isNull(value)) {
    return (dataScope.value.filter(item => {
      return item.value === value
    }))[0]
  }
}

const data = reactive({
  form: {},
  menuForm: {},
  dataScopeForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
  },
  rules: {
    name: [
      {required: true, message: "角色名称不能为空", trigger: "blur"},
      {max: 100, message: "角色名称长度不能超过 100 个字符", trigger: "blur"}
    ],
    memo: [
      {max: 255, message: "备注内容长度不能超过 255 个字符", trigger: "blur"}
    ]
  }
})

const {queryParams, form, menuForm, dataScopeForm, rules} = toRefs(data)

onMounted(() => {
  getList()
})

/** 查询角色列表 */
function getList() {
  loading.value = true
  getRolePageList(queryParams.value).then(result => {
    roleList.value = result.list
    total.value = result.total
    loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirmAndExecuteJS('是否确认删除名称为"' + row.name + '"的数据项?', delRole, row.id, getList)
}

/** 更多操作 */
function handleCommand(command, row) {
  switch (command) {
    case "handleDataScope":
      handleDataScope(row)
      break
    case "handleMenu":
      handleMenu(row)
      break
    default:
      break
  }
}

/** 重置新增的表单以及其他数据  */
function resetRoleForm() {
  form.value = {
    id: undefined,
    name: undefined,
    sort: 0,
    memo: undefined
  }
  proxy.resetForm("roleRef")
}

/** 添加角色 */
function handleAdd() {
  resetRoleForm()
  openRoleDialog.value = true
  title.value = "添加角色"
}

/** 修改角色 */
function handleUpdate(row) {
  resetRoleForm()
  const id = row.id
  getRole(id).then(role => {
    form.value = role
    openRoleDialog.value = true
    title.value = "修改角色"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (!valid) return;
    if (form.value.id !== undefined) {
      updateRole(form.value).then(() => {
        proxy.$modal.msgSuccess("修改成功")
        openRoleDialog.value = false
        getList()
      })
    } else {
      addRole(form.value).then(() => {
        proxy.$modal.msgSuccess("新增成功")
        openRoleDialog.value = false
        getList()
      })
    }
  })
}

/** 取消按钮 */
function cancel() {
  openRoleDialog.value = false
  resetRoleForm()
}

/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value, objectRef) {
  for (let i = 0; i < treeKeys.value.length; i++) {
    objectRef.store.nodesMap[treeKeys.value[i]].expanded = value
  }
}

/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value, objectRef) {
  objectRef.setCheckedKeys(value ? treeKeys.value : [])
}

/** 树权限（父子联动） */
function handleCheckedTreeConnect(value) {
  treeCheckStrictly.value = !!value
}

/** 所有部门节点数据 */
function getDeptAllCheckedKeys() {
  // 目前被选中的部门节点
  let checkedKeys = deptRef.value.getCheckedKeys()
  // 半选中的部门节点
  let halfCheckedKeys = deptRef.value.getHalfCheckedKeys()
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
  return checkedKeys
}

/** 选择角色数据权限触发 */
function dataScopeSelectChange(value) {
  if (value !== "2") {
    deptRef.value.setCheckedKeys([])
  }
}

function setTreeCheckStrictly() {
  setTimeout(()=> {
    treeCheckStrictly.value = true
  },50)
}

function resetCommonParams() {
  treeKeys.value = []
  treeCheckedKeys.value = []
  treeExpand.value = false
  treeNodeAll.value = false
  treeCheckStrictly.value = false
}

/** 重置数据权限表单以及其他数据  */
async function resetDataScopeForm() {
  resetCommonParams()
  dataScopeForm.value = {
    id: undefined,
    name: undefined,
    dataScope: undefined,
    dataScopeDeptIds: [],
  }
  proxy.resetForm("dataScopeFormRef")
}

/** 设置数据权限操作 */
async function handleDataScope(row) {
  openDataScopeDialog.value = true
  title.value = "设置数据权限"
  // 重置表单
  await resetDataScopeForm()
  // 获取部门树
  const deptTree = await getDeptTree(null)
  deptOptions.value = deptTree
  collectPropValues(deptTree, 'id', treeKeys.value)
  // 获取角色信息
  const role = await getRole(row.id)
  dataScopeForm.value = role
  // 获取部门ID列表
  const ids = await getDeptIdsByRoleId(row.id)
  treeCheckedKeys.value = ids
  //设置父子联动
  setTreeCheckStrictly()
}

/** 提交按钮（数据权限） */
function submitDataScope() {
  if (dataScopeForm.value.id !== undefined) {
    dataScopeForm.value.dataScopeDeptIds = getDeptAllCheckedKeys();
    updateRoleDataScope(dataScopeForm.value).then(response => {
      proxy.$modal.msgSuccess("修改成功")
      openDataScopeDialog.value = false
      getList()
    })
  }
}

/** 取消按钮（数据权限）*/
function cancelDataScope() {
  openDataScopeDialog.value = false;
  resetRoleForm();
}

/** 查询菜单树结构 */
function getAllMenuTreeSelect() {
  getAllMenuTree().then(allMenus => {
    menuOptions.value = allMenus;
    collectPropValues(allMenus, 'id', treeKeys.value)
  });
}

/** 重置数据权限表单以及其他数据  */
function resetMenuForm() {
  resetCommonParams()
  menuForm.value = {
    id: undefined,
    name: undefined,
    menuIds: []
  }
  proxy.resetForm("menuFormRef")
}

/** 设置菜单权限操作 */
function handleMenu(row) {
  resetMenuForm()
  getAllMenuTreeSelect()
  let roleMenuIds = []
  getRoleMenuIds(row.id).then((res) => {
    roleMenuIds = res
    treeCheckedKeys.value = roleMenuIds
  })
  getRole(row.id).then(role => {
    menuForm.value = role
  })
  title.value = "设置菜单权限"
  openMenuDialog.value = true
  //设置父子联动
  setTreeCheckStrictly()
}

/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
  // 目前被选中的菜单节点
  let checkedKeys = menuRef.value.getCheckedKeys()
  // 半选中的菜单节点
  let halfCheckedKeys = menuRef.value.getHalfCheckedKeys()
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
  return checkedKeys
}

/** 提交按钮（菜单权限） */
function submitMenu() {
  if (menuForm.value.id !== undefined) {
    menuForm.value.menuIds = getMenuAllCheckedKeys()
    updateRoleMenu(menuForm.value).then(() => {
      proxy.$modal.msgSuccess("修改成功")
      openMenuDialog.value = false
      getList()
    })
  }
}

/** 取消按钮（菜单权限）*/
function cancelMenu() {
  openMenuDialog.value = false
  resetRoleForm()
}

</script>

<template>
  <div class="app-container">
    <el-form @submit.native.prevent :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="角色名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入角色名称"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:role:add']"
        >新增
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" v-show="total > 0"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="roleList">
      <el-table-column label="角色名称" prop="name" :show-overflow-tooltip="true" min-width="150"/>
      <el-table-column prop="updateRoleDataScope" label="数据权限" width="200">
        <template #default="scope">
          {{ getDataScope(scope.row.dataScope).label }}
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="sort" width="100"/>
      <el-table-column label="修改时间" align="left" prop="updateTime" width="180"/>
      <el-table-column label="新建时间" align="left" prop="createTime" width="180"/>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding" min-width="140">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:role:update']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:role:delete']">删除
          </el-button>

          <el-button link type="primary" icon="CircleCheck" @click="handleMenu(scope.row)"
                     v-hasPermi="['system:role:operateMenu']">菜单权限
          </el-button>
          <el-button link type="primary" icon="CircleCheck" @click="handleDataScope(scope.row)"
                     v-hasPermi="['system:role:operateDataScope']">数据权限
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="openRoleDialog" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" maxlength="100"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" controls-position="right" :min="0"/>
        </el-form-item>
        <el-form-item label="备注" prop="memo">
          <el-input v-model="form.memo" type="textarea" placeholder="请输入内容" maxlength="255"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设置角色数据权限对话框 -->
    <el-dialog :title="title" v-model="openDataScopeDialog" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="dataScopeFormRef" :model="dataScopeForm" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="dataScopeForm.name" :disabled="true"/>
        </el-form-item>
        <el-form-item label="数据权限">
          <el-select v-model="dataScopeForm.dataScope" @change="dataScopeSelectChange">
            <el-option
                v-for="dict in dataScope"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据权限" v-show="dataScopeForm.dataScope === 2">
          <el-checkbox v-model="treeExpand" @change="handleCheckedTreeExpand($event, deptRef)">展开/折叠</el-checkbox>
          <el-checkbox v-model="treeNodeAll" @change="handleCheckedTreeNodeAll($event, deptRef)">全选/全不选
          </el-checkbox>
          <el-checkbox v-model="treeCheckStrictly" @change="handleCheckedTreeConnect($event)">父子联动
          </el-checkbox>
          <el-tree
              ref="deptRef"
              class="tree-border"
              :data="deptOptions"
              show-checkbox
              node-key="id"
              empty-text="加载中，请稍候"
              :check-strictly="!treeCheckStrictly"
              :props="{ label: 'name', children: 'children' }"
              :default-checked-keys="treeCheckedKeys"
          ></el-tree>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDataScope">确 定</el-button>
          <el-button @click="cancelDataScope">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设置角色菜单权限对话框 -->
    <el-dialog :title="title" v-model="openMenuDialog" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="menuFormRef" :model="menuForm" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="menuForm.name" :disabled="true"/>
        </el-form-item>

        <el-form-item label="菜单权限">
          <el-checkbox v-model="treeExpand" @change="handleCheckedTreeExpand($event, menuRef)">展开/折叠</el-checkbox>
          <el-checkbox v-model="treeNodeAll" @change="handleCheckedTreeNodeAll($event, menuRef)">全选/全不选
          </el-checkbox>
          <el-checkbox v-model="treeCheckStrictly" @change="handleCheckedTreeConnect($event)">父子联动
          </el-checkbox>
          <el-scrollbar max-height="500px" always class="custom-tree-scrollbar">
            <el-tree
                ref="menuRef"
                style="margin-bottom: 0;"
                :data="menuOptions"
                show-checkbox
                node-key="id"
                :check-strictly="!treeCheckStrictly"
                empty-text="加载中，请稍候"
                :props="{ label: 'name', children: 'children' }"
                :default-checked-keys="treeCheckedKeys"
            ></el-tree>
          </el-scrollbar>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer mt20">
          <el-button type="primary" @click="submitMenu">确 定</el-button>
          <el-button @click="cancelMenu">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped>
  .custom-tree-scrollbar {
    padding-top:5px;
    padding-bottom:0;
    border:1px solid #e5e6e7;
    background:#fff none;
    border-radius:4px;
    width:100%
  }
</style>/
